import {useState, useEffect} from 'react';
import TrackPlayer, {State, Event} from 'react-native-track-player';

const usePlaybackState = () => {
  const [state, setState] = useState(State.None);

  useEffect(() => {
    let unmounted = false;
    async function setPlayerState() {
      const playerState = await TrackPlayer.getState();
      if (!unmounted) {
        setState(playerState);
      }
    }

    setPlayerState();

    const sub = TrackPlayer.addEventListener(Event.PlaybackState, data => {
      if (!unmounted) {
        setState(data.state);
      }
    });

    return () => {
      unmounted = true;
      sub.remove();
    };
  }, []);

  return state;
};

export default usePlaybackState;
